package com.sz.web.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sz.web.model.ApiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应处理
 *
 * @author: yxl
 * 2025-07-24
 */

@ControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    public ResponseResultAdvice(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果已经是 ApiResponse，直接返回
        if (body instanceof ApiResponse<?>) {
            return body;
        }

        // 处理 null 或 Void 类型
        if (body == null || Void.class.isAssignableFrom(returnType.getParameterType())) {
            return ApiResponse.success(null);
        }

        // String 类型特殊处理
        if (body instanceof String) {
            try {
                return objectMapper.writeValueAsString(ApiResponse.success((String) body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("序列化失败", e);
            }
        }

        // 其他类型统一包装
        return ApiResponse.success(body);
    }
}
